﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using Medianamik.Core;
using Medianamik.Core.Urls;
using Medianamik.UI.Web.Shop.Data;
using SubSonic;

namespace Medianamik.UI.Web.Shop.ActionHandler
{
    public class UrlActionHandler : Medianamik.UI.Controls.UrlActionHandler
    {
        protected override Medianamik.Core.Urls.PathSegmentCollection GetSegments(Node node, List<Medianamik.Core.Node> orderedParentNodes, System.Globalization.CultureInfo culture)
        {
            var segments = base.GetSegments(node, orderedParentNodes, culture);

            //todo a mettre dans un fichier ressource ou web.config pour le products et produits
            if (node.NodeType.Inherits(BaseProduct.TYPE_ID) 
                || node.TypeId == BaseProduct.TYPE_ID)
            {
                var productSegments = new PathSegmentCollection();

                if(culture.Name.ToLower() == "fr-ca")
                {
                    productSegments.Add(0, new PathSegment("produits"));    
                }
                else
                {
                    productSegments.Add(0, new PathSegment("products"));  
                }

                foreach (var item in segments)
                {
                    productSegments.Add(item.Key + 1, item.Value);
                }

                segments = productSegments;
            }

            return segments;
        }

        protected override List<Medianamik.Core.Node> GetOrderedParentNodes(Medianamik.Core.Node node)
        {
            var nodes = base.GetOrderedParentNodes(node);
            const string productsInCategories = "Categories";

            if (node.NodeType.Inherits(BaseProduct.TYPE_ID) || node.TypeId == BaseProduct.TYPE_ID)
            {
                if (node.DefaultInstance.Properties.Exists(productsInCategories))
                {
                    var categories = node.DefaultInstance[productsInCategories].GetValue<List<Guid>>();
                    
                    if(categories.Count() > 0)
                    {
                        var categoryId = categories.First();

                        var category = NodeManager.GetNode(categoryId);
                           nodes = base.GetOrderedParentNodes(category);
                           nodes.Add(category);
                    }
                }
            }

            return nodes;
        }
    }
}
